<?php

namespace app\scm\controller;

use app\admin\common\Base;
use think\Db;
use app\scm\model\Invoice as Model;
use app\admin\common\Excel;
//采购开票
class Purchasebilling extends Base
{
    public function index()
    {
        $data = $this->request->param();

        if (isset($data['ajax']) && $data['ajax'] == 100) {
            $map = [];
            $page = isset($data['page']) ? $data['page'] : 1;
            $page = intval($page);
            $limit = isset($data['rows']) ? $data['rows'] : 10;
            $limit = intval($limit);
            $start = $limit * ($page - 1);

            if (isset($data['startdate']) && isset($data['enddate'])) {
                $month = $this->get_month_start_to_end($data['startdate'], $data['enddate']);
            } else {
                $month = $this->get_month_start_to_end();
            }
            $map['dj_time']=['between',[$month['month_start'],$month['month_end']]];//按时间查询
            if(isset($data['invoice_no']) && $data['invoice_no'] != ''){
                $map['invoice_no']=['eq',  $data['invoice_no']]; //发票号
            }
            if(isset($data['invoice_title']) && $data['invoice_title'] != ''){
                $map['invoice_title']=['eq',  $data['invoice_title']]; //发票抬头
            }
            $list = Db::name('invoice')->where($map)->where('is_del', 0)->where('type', 0)->where('enterprise_id', $this->EnterpriseId)->order('dj_time desc,id desc')->select();
            foreach ($list as $key => $val) {
                $o=$this->order_one($val['pid']);
                if(isset($data['gl_sn'])&&$data['gl_sn']!=''){//单据编号
                    if($o['sn']!=$data['gl_sn']){
                        unset($list[$key]);
                        continue;
                    }
                }
               
                if(isset($data['user_id']) && $data['user_id'] != ''){//供应商
                    $user_id_arr = explode(',',$data['user_id']);
                    if(!in_array($o['user_id'], $user_id_arr)){
                        unset($list[$key]);
                        continue;
                    }
                }
                //按单据时间查询
                if (isset($data['dj_startdate']) && isset($data['dj_enddate'])&&$data['dj_startdate']!=''&&$data['dj_enddate']!='') {
                    $dj_month = $this->get_month_start_to_end($data['dj_startdate'], $data['dj_enddate']);
                } else {
                    $dj_month = $this->get_month_start_to_end();
                }
                if ($o['time_dj_time']<$dj_month['month_start']||$o['time_dj_time']>$dj_month['month_end']) {
                    unset($list[$key]);
                    continue;
                }
                $list[$key]['gl_dj_time']= $o['dj_time'];
                $list[$key]['gl_sn']= $o['sn'];
                $list[$key]['o_type']= $o['o_type'];
                $list[$key]['gl_c_name']= $o['c_name'];
                $list[$key]['gl_jine']= $o['jine_sum'];//金额
                $list[$key]['gl_tax_e_sum']= $o['tax_e_sum'];//税额
                $list[$key]['gl_total_price_sum']= $o['total_price_sum'];//价税合计
                $list[$key]['dj_time'] = date('Y-m-d', $val['dj_time']);
                $list[$key]['pay_status_name']= $o['pay_status_name'];//付款状态  
            }
            $count =count($list);
            $list = array_slice($list, $start, $limit);
            if(isset($data['is_export']) && $data['is_export'] == 1){//如果是导出操作
                return $this->export($list);
            }
            return $this->grid_data($list, $count, $page, $limit);
        }
        return $this->fetch();
    }

     public function export($volist){
        $excel = new Excel();
        $title = [
            'gl_dj_time' => '单据日期',
            'gl_sn' => '单据编号',
            'gl_c_name' => '供应商',
            'gl_jine' => '金额',
            'gl_tax_e_sum' => '税额',
            'gl_total_price_sum'=>"价税合计",
            'pay_status_name'=>'付款状态',
            'dj_time'=>'开票日期',
            'invoice_price'=>'开票金额',  
            'invoice_no'=>'发票号', 
            'invoice_title'=>'发票抬头', 
        ]; 
        $arr_list=[];
        if(!empty($volist)){
           $arr_list=$volist;
        }

        //添加标题到数组头部
        array_unshift($arr_list,$title);
        $kong_arr=$title;
        foreach ($kong_arr as $ke1 => $va1) {
            $kong_arr[$ke1]='';
        }
        for ($i=0; $i <3 ; $i++) { 
            array_unshift($arr_list,$kong_arr);
        }
        //根据此参数获取数据中的值，要与表格标题键名对应
        $keys=[];
        foreach ($title as $k2 => $v2) {
            array_push($keys, $k2);
        }

        $merge=[];
        $options=[
            'alignCenter'=>['A','B','C','D','E','F','G','H','I','J','K'],//居中
            'bold'=>['A1:K3','A4:K4'],//加粗
            'fontSize'=>['zimu'=>['A1'],'size'=>20],//字体大小
        ];
        $title=[//标题
            'title'=>"采购单开票记录",
            'max_zimu'=>"K",
            'number'=>'3',
        ];
        $excel_export_title="采购开票记录导出_" . date('Y-m-d_His') . '.xlsx';//文件名称
        $excel->exportExcel($arr_list,$keys,$excel_export_title,$options,-1,$merge,$title);
        exit();
    }

    public function add_export($volist){
        $excel = new Excel();
        $title = [
            'dj_time' => '单据日期',
            'sn' => '单据编号',
            'o_type_name' => '单据类型',
            'c_name' => '供应商',
            'pay_status_name' => '付款状态',
            'jine_sum'=>'金额',
            'tax_e_sum'=>'税额',
            'total_price_sum'=>"价税合计",
            'y_invoice_price'=>'已开票金额',
            'w_invoice_price'=>'未开票金额',
        ]; 
        $arr_list=[];
        if(!empty($volist)){
           $arr_list=$volist;
        }

        //添加标题到数组头部
        array_unshift($arr_list,$title);
        $kong_arr=$title;
        foreach ($kong_arr as $ke1 => $va1) {
            $kong_arr[$ke1]='';
        }
        for ($i=0; $i <3 ; $i++) { 
            array_unshift($arr_list,$kong_arr);
        }
        //根据此参数获取数据中的值，要与表格标题键名对应
        $keys=[];
        foreach ($title as $k2 => $v2) {
            array_push($keys, $k2);
        }

        $merge=[];
        $options=[
            'alignCenter'=>['A','B','C','D','E','F','G','H','I','J'],//居中
            'bold'=>['A1:J3','A4:J4'],//加粗
            'fontSize'=>['zimu'=>['A1'],'size'=>20],//字体大小
        ];
        $title=[//标题
            'title'=>"采购开票",
            'max_zimu'=>"J",
            'number'=>'3',
        ];
        $excel_export_title="采购开票记录导出_" . date('Y-m-d_His') . '.xlsx';//文件名称
        $excel->exportExcel($arr_list,$keys,$excel_export_title,$options,-1,$merge,$title);
        exit();
    }



    public function add()
    {
        $data = $this->request->param();

        if (isset($data['ajax']) && $data['ajax'] == 100) {
            $map = [];
            $page = isset($data['page']) ? $data['page'] : 1;
            $page = intval($page);
            $limit = isset($data['rows']) ? $data['rows'] : 10;
            $limit = intval($limit);
            $start = $limit * ($page - 1);

            if (isset($data['startdate']) && isset($data['enddate'])) {
                $month = $this->get_month_start_to_end($data['startdate'], $data['enddate']);
            } else {
                $month = $this->get_month_start_to_end();
            }
            $map['dj_time']=['between',[$month['month_start'],$month['month_end']]];//按时间查询
            if(isset($data['user_id']) && $data['user_id'] != ''){
                $map['user_id']=['in',  $data['user_id']]; //供应商 
            }
            if(isset($data['sn']) && $data['sn'] != ''){
                $data['sn']=explode(',', $data['sn']);
                $map['sn']=['in',  $data['sn']]; //单据编号 
            }
            $sql = Db::name('order')->where(['is_del' => 0, 'enterprise_id' => $this->EnterpriseId]);
            $sql = $sql->where($map)->where('o_type','in',[4,5])->where('status',1);
            $volist = $sql->order('dj_time desc ,id desc')->select();
            $list0=$this->order_list($volist,-1);
            foreach ($list0 as $key => &$val) {
                $val['y_invoice_price'] = sprintf("%.2f",Db::name('invoice')->where('type', 0)->where(['is_del' => 0, 'enterprise_id' => $this->EnterpriseId])->where('pid', $val['id'])->sum('invoice_price'));
                $val['w_invoice_price'] = sprintf("%.2f",$val['total_price_sum'] -  $val['y_invoice_price']);
            }
            // foreach ($list0 as $ke => $va) {
            //     if(isset($data['is_tax_e_zero'])&&$data['is_tax_e_zero']==1){//税额为0的不显示
            //         if($va['tax_e_sum']=="0"){
            //             unset($list0[$ke]);
            //         }
            //     }
            // }
            $list0=$this->formart_list($list0,$data,'is_tax_e_zero',[1,'tax_e_sum']);
            $list0=$this->formart_list($list0,$data,'is_kp_all',[0,'y_invoice_price','total_price_sum']);
            // foreach ($list0 as $ke => $va) {
            //     if(!isset($data['is_kp_all'])||$data['is_kp_all']==0){//全部开票的不显示
            //         if($val['y_invoice_price']==$val['total_price_sum']){
            //             unset($list0[$ke]);
            //         }
            //     }
            // }
            //halt($list0);
            $count =count($list0);
            $list = array_slice($list0, $start, $limit);
            if(isset($data['is_export']) && $data['is_export'] == 1){//如果是导出操作
                return $this->add_export($list);
            }
            return $this->grid_data($list, $count, $page, $limit);
        }

        return $this->fetch();
    }
    function formart_list($volist,$data,$key,$arr){
        $arr_list=[];
        foreach ($volist as $ke => $val) {
            if($arr[0]==0){
                if(!isset($data[$key])||$data[$key]==0){//全部开票的不显示
                    if($val[$arr[1]]!=$val[$arr[2]]){
                        array_push($arr_list,$val);
                    }
                }else{
                    array_push($arr_list,$val);
                }
                
            }elseif ($arr[0]==1) {
                if(isset($data[$key])&&$data[$key]==1){//税额为0的不显示
                    if($val[$arr[1]]!="0"){
                        array_push($arr_list,$val);
                    }
                }else{
                    array_push($arr_list,$val);
                }
            }
        }
        return $arr_list;
    }

    //编辑栏目1-2
    public function save()
    {
        $status = 0;
        $msg = "操作失败";
        $data = $this->request->param();
        $arr = [];
        foreach ($data['movedata'] as $key => $value) {
            $arr[$key]['pid'] = $value['id'];
            $arr[$key]['addtime'] = time();
            $arr[$key]['updatetime'] = time();
            $arr[$key]['dj_time'] = strtotime($data['dj_time']);
            $arr[$key]['invoice_no'] = $data['invoice_no'];
            $arr[$key]['invoice_price'] = $value['invoice_price'];
            $arr[$key]['invoice_title'] = $data['invoice_title'];
            $arr[$key]['enterprise_id'] = $this->EnterpriseId;
            $arr[$key]['type'] = 0;
        }
        $model = new Model();
        $result = $model->allowField(true)->saveAll($arr);
        if ($result) {
            return json(['status' => 1, 'msg' => '操作成功']);
        } else {
            return json(['status' => $status, 'msg' => $msg]);
        }
    }

    //删除栏目1-1
    public function del($id)
    {
        $status = 0;
        $msg = "操作失败";
        $del = Db::name('invoice')->where('id','in', $id)->update(["is_del" => 1,'updatetime'=>time()]);
        if ($del) {
            $status = 1;
            $msg = "删除成功";
        }
        return json(['status' => $status, 'msg' => $msg]);
    }
}
